import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import getuser from '../../../atoms/getuser';
import { tbclass, tbteam } from '../../../atoms/db';



const logger = anylogger('pages/api/teamglz/query.api');

export type IData = ITbteam & {
	classname: string;
	grade: string;
};

export type Result = {
	count: number;
	data: IData[];
};

export type Query = {
	q: string;
	page: string;
	pagesize: string;
	id: string;
}
/**
 * 列表查询服务
 */
const handler = an48<Result>();
handler.get(async (req, res) => {
	try {
		logger.debug('msg query:', req.query);
		const { q, id, ...rest } = req.query as Query;
		const page = Number(rest.page || '1');
		const pagesize = Number(rest.pagesize || '10');
		const user = await getuser(req);
		if (!user || user.role !== 'admin') {
			res.status(200).json({
				count: 0,
				data: []
			});
			return;
		}
		const dt1 = tbteam();
		if (q) {
			const query = q.trim();
			dt1.where('grade', 'like', `%${query}%`)
				.orWhere('class_id', 'like', `%${query}%`)
				.orWhere('classname', 'like', `%${query}%`)
				.orWhere('team_id', 'like', `%${query}%`)
				.orWhere('teamname', 'like', `%${query}%`)
				.orWhere('teammate', 'like', `%${query}%`);
		}
		const [{ size }] = await dt1
			.count('*', { as: 'size' });
		const count = Number(size);
		const dt2 = tbteam();
		if (q && typeof q === 'string') {
			const query = q.trim();
			dt2.where('grade', 'like', `%${query}%`)
				.orWhere('class_id', 'like', `%${query}%`)
				.orWhere('classname', 'like', `%${query}%`)
				.orWhere('team_id', 'like', `%${query}%`)
				.orWhere('teamname', 'like', `%${query}%`)
				.orWhere('teammate', 'like', `%${query}%`);
		}
		const offset = (page - 1) * pagesize;
		const d = await dt2
			.select('*')
			.limit(pagesize)
			.offset(offset)
			.orderBy('classname', 'asc')
			.orderBy('teamname', 'asc')
			.orderBy('teammate', 'asc')
			.orderBy('team_id', 'asc')
			.orderBy('class_id', 'asc');
		const dataclass = await tbclass().select('*');
		const mapclass = dataclass.reduce((pre, cur) => {
			return pre.set(cur.class_id, cur.classname);
		}, new Map<string, string>());
		const data = d.map((it) => {
			const classname = mapclass.get(it.class_id);
			return {
				...it,
				classname
			} as IData;
		});
		res.status(200).json({

			data,
			count
		});
	} catch (error) {
		logger.trace(error);
		res.status(200).json({
			count: 0,
			data: []
		});
	}
});

export const config = {} as PageConfig;

export default handler;

